package com.viewpagerindicator.sample;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
import com.viewpagerindicator.sample.adapters.GoodsItemAdapter;
import com.viewpagerindicator.sample.beans.Goods;
import com.viewpagerindicator.sample.util.ACache;
import com.viewpagerindicator.sample.util.BluetoothUtils;
import com.viewpagerindicator.sample.util.ImageLoaderUtils;
import com.viewpagerindicator.sample.util.URLs;
import com.viewpagerindicator.sample.view.LoginDialog;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import cz.msebera.android.httpclient.Header;

/**
 * Created by zhao on 2015/11/8.
 */
public class GoodsDetailActivity extends AppCompatActivity implements View.OnClickListener{
    private String goodsid;
    View contentViewBg;
    View progressBg;
    View errorMsgBg;
    View printBg;

    TextView goodsNameTv;
    TextView goodsMarkTv;
    TextView goodsDescTv;
    TextView goodsPriceDescTv;
    ListView listView;
    TextView printingTextView;
    ImageView thumbImageView;
    GoodsItemAdapter adapter;
    List<JSONObject> goodsItems=new ArrayList<>();
    BluetoothAdapter bluetoothAdapter ;
    BluetoothUtils bluetoothUtils;
    String uuid = "00001101-0000-1000-8000-00805F9B34FB";
    Handler handler;
    BluetoothSocket clienSocket;
    InputStream inputStream;
    OutputStream outputStream;
    JSONObject itemObject;
    Button shoucangBtn;
    Button tobuyBtn;
    ImageLoader imageLoader;
    //蓝牙相关
    CutokApplication application;

    //event of activityResult
    public static final int REQUESTID_OF_CHOICEBLUEDEVICE=100;

    private final static String TAG = GoodsDetailActivity.class.getSimpleName();
    private BluetoothLeService mBluetoothLeService;
    private boolean mConnected = false;
    ACache mCache ;
    Md5FileNameGenerator md5FileNameGenerator;
    public String lastOrderFileUrl=null;
    Goods goods=null;
    /***
     * paypal 相关配置
     *
     * - Set to PayPalConfiguration.ENVIRONMENT_PRODUCTION to move real money.
     *
     * - Set to PayPalConfiguration.ENVIRONMENT_SANDBOX to use your test credentials
     * from https://developer.paypal.com
     *
     * - Set to PayPalConfiguration.ENVIRONMENT_NO_NETWORK to kick the tires
     * without communicating to PayPal's servers.
     */
    private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;

    // note that these credentials will differ between live & sandbox environments.
    private static final String CONFIG_CLIENT_ID = "AYTniYDpnMMYQAJqC7ktKRrzm9ii8eRkAJxq-bE7pZLXWKOBC_D5uK9uLG-7s-WMocTUEY4EsVNyzNM4";
    private static final int REQUEST_CODE_PAYMENT = 1;
    private static PayPalConfiguration config = new PayPalConfiguration()
            .environment(CONFIG_ENVIRONMENT)
            .clientId(CONFIG_CLIENT_ID)
                    // The following are only used in PayPalFuturePaymentActivity.
            .merchantName("Example Merchant")
            .merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
            .merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.goods_detail_layout);
        Intent intent = new Intent(this, PayPalService.class);
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
        startService(intent);
        mCache=ACache.get(this);
        md5FileNameGenerator=new Md5FileNameGenerator();
        application= (CutokApplication) getApplication();
        contentViewBg=findViewById(R.id.goodsdetail_bg);
        progressBg=findViewById(R.id.progress_bg);
        errorMsgBg=findViewById(R.id.errormsg_bg);
        printBg=findViewById(R.id.printing_bg);
        printingTextView= (TextView) findViewById(R.id.print_msg);
        listView= (ListView) findViewById(R.id.goods_item_listview);
        goodsid=getIntent().getStringExtra("goodsid");
        bluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
        bluetoothUtils=new BluetoothUtils(this,bluetoothAdapter);
        goodsNameTv= (TextView) findViewById(R.id.goods_name);
        goodsMarkTv= (TextView) findViewById(R.id.goods_mark);
        goodsDescTv= (TextView) findViewById(R.id.goods_desc);
        goodsPriceDescTv= (TextView) findViewById(R.id.goods_price);
        shoucangBtn= (Button) findViewById(R.id.goods_shoucang);
        tobuyBtn= (Button) findViewById(R.id.goods_buy);
        thumbImageView= (ImageView) findViewById(R.id.goods_thumb);
        adapter=new GoodsItemAdapter(this,R.layout.goods_item_item,goodsItems);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                JSONObject jsonObject = (JSONObject) view.getTag();
                try {
                    String itemId = jsonObject.getString("order_file");
                    wgetItem(URLs.domain + itemId);
                } catch (Exception e) {
                    Toast.makeText(GoodsDetailActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
        imageLoader= ImageLoaderUtils.getInstance(this);
        initData(goodsid);
        shoucangBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences mySharedPreferences = getSharedPreferences("test", Activity.MODE_MULTI_PROCESS);
                SharedPreferences.Editor editor = mySharedPreferences.edit();
                String collections = mySharedPreferences.getString("collections", "");
                if (collections.contains("," + goodsid + ",")) {
                    //已经收藏过了
                    Toast.makeText(GoodsDetailActivity.this, getString(R.string.collection_ed), Toast.LENGTH_SHORT).show();
                } else {
                    editor.putString("collections", collections + "," + goodsid + ",");
                    editor.commit();
                    Toast.makeText(GoodsDetailActivity.this, getString(R.string.collection_success), Toast.LENGTH_SHORT).show();
                }
            }
        });
        tobuyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!application.isLogined()){
                    showDialogLogin();
                }else{
                    redirctToPay();
                }
            }
        });
        errorMsgBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initData(goodsid);
            }
        });
    }
    private PayPalPayment getThingToBuy(String paymentIntent) {
        return new PayPalPayment(goods.getPrice(), "USD", goods.getName(),
                paymentIntent);
    }


    /**
     * 获取商品详情
     * */
    public void initData(String id){
        showView(progressBg);
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams requestParams=new RequestParams();
        requestParams.put("id", id);
        requestParams.put("sessionid", application.getSessionId());
        client.get(URLs.goodsdetail, requestParams, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                //解析数据
                try {
                    Goods temp = Goods.parseWithItem(responseBody);
                    goods = temp;
                    if (temp != null) {
                        goodsNameTv.setText(temp.getName());
                        goodsDescTv.setText(temp.getDesc());
                        goodsMarkTv.setText(temp.getRemark());
                        if (temp.getPrice().compareTo(new BigDecimal(0)) == 0) {
                            tobuyBtn.setVisibility(View.GONE);
                            goodsPriceDescTv.setText(getString(R.string.goods_price_tip));
                        } else {
                            if (temp.isBuyed()) {
                                tobuyBtn.setVisibility(View.GONE);
                            } else {
                                tobuyBtn.setVisibility(View.VISIBLE);
                            }
                            goodsPriceDescTv.setText("$ " + temp.getPrice().toString());
                        }
                        imageLoader.displayImage(temp.getThumb(), thumbImageView);
                        goodsItems.clear();
                        goodsItems.addAll(temp.getItems());
                        adapter.notifyDataSetChanged();
                        showView(contentViewBg);
                    }
                } catch (Exception e) {
                    showView(errorMsgBg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                showView(errorMsgBg);
            }
        });
    }
    public void showView(View view2show){
        contentViewBg.setVisibility(View.GONE);
        progressBg.setVisibility(View.GONE);
        errorMsgBg.setVisibility(View.GONE);
        printBg.setVisibility(View.GONE);
        view2show.setVisibility(View.VISIBLE);
    }
    public void showView(View view2show,String title,String desc){
        contentViewBg.setVisibility(View.GONE);
        progressBg.setVisibility(View.GONE);
        errorMsgBg.setVisibility(View.GONE);
        printBg.setVisibility(View.GONE);
        if(title!=null){
            TextView titleTextView= (TextView) errorMsgBg.findViewById(R.id.errormsg_title);
            titleTextView.setText(title);
        }
        if(desc!=null){
            TextView titleTextView= (TextView) errorMsgBg.findViewById(R.id.errormsg_desc);
            titleTextView.setText(title);
        }
        view2show.setVisibility(View.VISIBLE);
    }
    public void wgetItem(String orderFile){
        showView(progressBg);
        lastOrderFileUrl=orderFile;
        final String cachePrefix=md5FileNameGenerator.generate(orderFile);
        final BluetoothDevice lastDevice=application.lastBluetoothDevice;
        if(mCache.getAsString(cachePrefix)!=null){
//            showBluetoothTip(lastDevice, (mCache.getAsString(cachePrefix)));
            showBluetoothTip(lastDevice,cachePrefix);
            return ;
        }
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(orderFile, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                //解析数据
                try {
                    String orderString = new String(responseBody);
                    mCache.put(cachePrefix, orderString);
//                    showBluetoothTip(lastDevice, orderString);
                    showBluetoothTip(lastDevice, cachePrefix);
                } catch (Exception e) {
                    showView(errorMsgBg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                showView(errorMsgBg);
            }
        });
    }
    public void showBluetoothTip(final BluetoothDevice bluetoothDevice,final String code2print){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        if(bluetoothDevice==null){
            builder.setTitle(R.string.havent_already_device);
            //如果没有已存的蓝牙设备，则提示用户去选择蓝牙设备
            builder.setNegativeButton(R.string.btn_cancle, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    showView(contentViewBg);
                    dialogInterface.dismiss();
                }
            });
            builder.setMessage(R.string.dialog_msg_tochoice);
            builder.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent intent=new Intent(GoodsDetailActivity.this,SspDeviceActivity.class);
                    startActivityForResult(intent,REQUESTID_OF_CHOICEBLUEDEVICE);
                    showView(contentViewBg);
                    dialogInterface.dismiss();
                }
            });
        }else{
            builder.setTitle(R.string.dialog_title_to);
            //如果存在lastDevice，则提示用户是否重新选择蓝牙设备
            builder.setNegativeButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                    Intent intent=new Intent(GoodsDetailActivity.this,SspPrintActivity.class);
                    intent.putExtra(SspPrintActivity.CONTENT_2_PRINT, code2print);
                    intent.putExtra(SspPrintActivity.EXTRAS_DEVICE_ADDRESS, bluetoothDevice.getAddress());
                    showView(contentViewBg);
                    startActivity(intent);
                    //去打印
                }
            });
            builder.setNeutralButton(R.string.btn_cancle, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                    showView(contentViewBg);
                }
            });
            String msg=bluetoothDevice.getName();
            if(msg==null){
                msg=""+bluetoothDevice.getAddress();
            }else{
                msg=msg+"("+bluetoothDevice.getAddress()+")";
            }
            builder.setMessage(msg);
            builder.setPositiveButton(R.string.dialog_btn_search, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
//                    Intent intent = new Intent(GoodsDetailActivity.this, DeviceActivity.class);
                    Intent intent = new Intent(GoodsDetailActivity.this, SspDeviceActivity.class);
                    startActivityForResult(intent, REQUESTID_OF_CHOICEBLUEDEVICE);
                    showView(contentViewBg);
                    dialogInterface.dismiss();
                }
            });
        }
        builder.show();
    }

    @Override
    public void onClick(View view) {
        if(goods.getPrice().compareTo(new BigDecimal(0))!=0){
            //点击item的按钮事件
            if(!application.isLogined()){
                showDialogLogin();
                return;
            }
            if(!goods.isBuyed()){
                //尚未购买uy
                showToBuyDialog();
                return;
            }
        }
        if(view.getTag()!=null){
            JSONObject jsonObject= (JSONObject) view.getTag();
            try{
                String itemId = jsonObject.getString("order_file");
                wgetItem(URLs.domain+itemId);
            }catch (Exception e){
                Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==REQUESTID_OF_CHOICEBLUEDEVICE){
            BluetoothDevice address =data.getParcelableExtra("address");
            application.lastBluetoothDevice=address;
            Toast.makeText(this,address.getAddress(),Toast.LENGTH_LONG).show();
            //连接蓝牙
            if(lastOrderFileUrl!=null&&address.getAddress()!=null){
                wgetItem(lastOrderFileUrl);
            }
        }else if (requestCode == REQUEST_CODE_PAYMENT) {
            //支付成功
            if (resultCode == Activity.RESULT_OK) {
                PaymentConfirmation confirm =data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
                if (confirm != null) {
                    try {
                        showNotifyPaymentToServer(confirm);
                        Log.i(TAG, confirm.toJSONObject().toString(4));
                        Log.i(TAG, confirm.getPayment().toJSONObject().toString(4));
                        /**
                         *  TODO: send 'confirm' (and possibly confirm.getPayment() to your server for verification
                         * or consent completion.
                         * See https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
                         * for more details.
                         *
                         * For sample mobile backend interactions, see
                         * https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
                         */
//                        Toast.makeText( getApplicationContext(), "PaymentConfirmation info received from PayPal", Toast.LENGTH_LONG) .show();

                    } catch (JSONException e) {
                        Log.e(TAG, "an extremely unlikely failure occurred: ", e);
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Log.i(TAG, "The user canceled.");
            } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
                Log.i( TAG, "An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
            }
        }
    }
    public void back(View view){
        finish();
    }

    public void showToBuyDialog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle(R.string.dialog_title);
        builder.setMessage(R.string.please_to_buy);
        builder.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.show();
    }
    public void showNotifyPaymentToServer(PaymentConfirmation confirmation){
        ProgressDialog.Builder builder=new ProgressDialog.Builder(this);
        builder.setTitle(R.string.progress_dialog_title);
        builder.setMessage(R.string.progress_dialog_commit_order);
        builder.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams requestParams=new RequestParams();
        requestParams.put("payment_json",confirmation.toJSONObject());
        requestParams.put("goods_id", goods.getId());
        requestParams.put("sessionid", application.getSessionId());
        final android.app.AlertDialog dialog=builder.create();
        client.post(URLs.postpayment, requestParams, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                JSONTokener jsonParser = new JSONTokener(new String(responseBody));
                try {
                    JSONObject person = (JSONObject) jsonParser.nextValue();
                    int status=person.getInt("status");
                    if(status>0){
                        dialog.setMessage("支付成功");
                    }else{
                        throw new Exception("支付校验失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    dialog.setMessage("支付失败");
                }
                initData(goodsid);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                String s = new String(responseBody);
                dialog.dismiss();
                showBuyFailedDialog();
            }
        });
        dialog.show();
    }
    public void redirctToPay(){
        PayPalPayment thingToBuy = getThingToBuy(PayPalPayment.PAYMENT_INTENT_SALE);
        Intent intent = new Intent(GoodsDetailActivity.this, PaymentActivity.class);
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
        intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
        startActivityForResult(intent, REQUEST_CODE_PAYMENT);
    }
    public void showBuyFailedDialog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle(R.string.dialog_title);
        builder.setMessage(R.string.dialog_buy_failed);
        builder.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.show();
    }
    public void showDialogLogin(){
        LoginDialog loginDialog=new LoginDialog(this,new LoginDialog.LoginEventLinster() {
            @Override
            public void logineed(boolean isSuccess) {
                if(isSuccess){
                    initData(goodsid);
                }else{
                    Toast.makeText(GoodsDetailActivity.this,getString(R.string.error_msg_login_error),Toast.LENGTH_LONG).show();
                }
            }
        });
        loginDialog.show();
    }
}
